package com.lanxiao.cloud.modules.oauth.domain.factory;

import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.modules.oauth.domain.service.ILoginService;
import com.lanxiao.cloud.common.core.error.LoginErrorType;
import java.util.HashMap;
import java.util.Map;
import com.lanxiao.cloud.modules.oauth.infrastructure.enums.LoginType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-08-24
 */
@Component
public class LoginFactory implements ApplicationContextAware {

  private static Map<LoginType, ILoginService> LOGIN_MAP;

  public ILoginService handle(LoginType type) {
    ILoginService loginService = LOGIN_MAP.get(type);
    BusinessException.isNull(loginService, LoginErrorType.LOGIN_TYPE_ERROR);
    return loginService;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    Map<String, ILoginService> beansOfType = applicationContext.getBeansOfType(ILoginService.class);
    LOGIN_MAP = new HashMap<>(beansOfType.size());
    beansOfType.forEach((k,v)->{ LOGIN_MAP.put(v.only(),v); });
  }

}
